#!/bin/bash
# Author: <fanyuantao>
# Date: 2021-08-20 10:50:00
# Description: This script is used to save file to remote server.

server=""
backup_dir="/home/1panel"

function check_backup_dir() {
    if [ ! -d "$backup_dir" ]; then
        echo "Backup directory $backup_dir does not exist."
    fi
    if [ ! -d "$backup_dir/system_images" ]; then
        echo "Backup directory $backup_dir/system_images does not exist."
    fi
    if [ ! -d "$backup_dir/1panel_compose" ]; then
        echo "Backup directory $backup_dir/1panel_compose does not exist."
    fi
    if [ ! -d "$backup_dir/minio_data" ]; then
        echo "Backup directory $backup_dir/minio_data does not exist."
    fi
    if [ ! -d "$backup_dir/bash_script" ]; then
        echo "Backup directory $backup_dir/bash_script does not exist."
    fi
}

function input_server_info() {
    echo ""
    echo "example: 192.168.1.100"
    read -p "Input remote server IP address: " ip
    if [[ -z $ip || ! $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo "Invalid input. Please enter the correct remote address."
        return 1
    else
        server_ip=$ip
    fi

    echo ""
    read -p "Input remote server username of $server_ip : " username
    if [[ -z $username ]]; then
        echo "Invalid input. Please enter the correct remote username."
        return 1
    else
        server_username=$username
    fi

    if ! ping -c 1 $server_ip > /dev/null 2>&1; then
        echo "Can not connect to remote server $server_ip."
        exit 1
    fi

    server="$server_username@$server_ip"
    echo $server
}

function save_file_to_remote() {
    input_server_info
    if ! ssh $server "test -d backup"; then
        ssh $server "mkdir -p backup"
    fi
    echo "Remote server connection successful."
    echo ""
    # upload backup file to remote server
    echo "Start to save file to remote server."
    scp -r $backup_dir $server:backup/
    ssh $server "echo $(date '+%Y-%m-%d %H:%M:%S') >> backup/bak.log"

    echo "Save file to remote server successfully."
}

function main() {
    check_backup_dir
    save_file_to_remote
}

main